﻿using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace QuickGet.EntityFrameworkCore.DesignTime
{
    public abstract class AbstractDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public abstract string DatabaseType { get; }

        public AppDbContext CreateDbContext(string[] args)
        {
            var sp = BuildDesignTimeServices(args, DatabaseType);
            return sp.GetRequiredService<AppDbContext>();
        }

        protected virtual IServiceProvider BuildDesignTimeServices(string[] args, string databaseType)
        {
            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.AddCommandLine(args)
                .AddEnvironmentVariables()
                .AddUserSecrets(this.GetType().Assembly, true, true);   // 加载Factory实例所在程序集UserSecretId

            var configuration = configurationBuilder.Build();

            var services = new ServiceCollection();
            services.AddScoped<IConfiguration>(sp => configuration);
            services.Configure<DatabaseOptions>(option => option.Type = databaseType);
            services.AddDbContext<AppDbContext>(DatabaseConfigureExtensions.ConfigureDatabaseProvider);

            var serviceProvider = services.BuildServiceProvider();

            return serviceProvider;
        }
    }
}
